const http = require('http')
const url = require('url')
const fs = require('fs')

function read() {
  return new Promise((resolve, reject) => {
    fs.readFile('./index.html', 'utf-8' ,(err, content) => {
      if (err) {
        reject(err.message)
      } else {
        resolve(content)
      }
    })
  })
}

http.createServer(async (req, res) => {
  let urlStr = req.url
  let { pathname } = url.parse(urlStr)

  switch(pathname) {
    case '/index.html':
      const content = await read()
      res.write(content)
      break
    case '/api/list':
      res.write(JSON.stringify({x: 0}))
      break
  }
  res.end()
}).listen(8080, () => {
  console.log('localhost:8080')
})